package com.huluobo.a2107kotlinshopping.cart

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2107kotlinshopping.R
import com.huluobo.a2107kotlinshopping.base.BaseMVVMFragment
import com.huluobo.a2107kotlinshopping.databinding.FragmentCartBinding
import org.w3c.dom.Text

class CartFragment : BaseMVVMFragment<FragmentCartBinding>() {

    private lateinit var viewModel: CartViewModel
    override fun getLayoutId(): Int = R.layout.fragment_cart

    private lateinit var adapter: CartAdapter

    private val cartList = mutableListOf<CartBean>()

    override fun initData() {
        viewModel = ViewModelProvider(requireActivity())[CartViewModel::class.java]

        viewModel.getCartList()

        viewModel.getCartListSuccess.observe(this) {
            if (it.code == 200) {
                cartList.clear()
                cartList.addAll(it.data)
                adapter.notifyDataSetChanged()
                it.data.forEach {
                    Log.i("TagA", "cart:${it.isChecked}")
                }
            }
        }
        viewModel.deleteCartSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.addSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong("购物车数量+1")
            }
        }

        viewModel.removeSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong("购物车数量-1")
            }
        }
    }

    override fun initView() {
        dataBinding.cartRv.layoutManager = LinearLayoutManager(requireContext())
        adapter = CartAdapter(cartList)
        dataBinding.cartRv.adapter = adapter

        //全选按钮点击事件
        dataBinding.cartCbSelectAll.setOnCheckedChangeListener { buttonView, isChecked ->
            if (cartList.size > 0) {
                cartList.map {
                    //遍历lit中每一个值,可以替换为循环
                    it.isChecked = isChecked
                }

                adapter.notifyDataSetChanged()
                totalPrice()
            }
        }

        adapter.addChildClickViewIds(
            R.id.cart_item_cb,
            R.id.cart_item_delete,
            R.id.cart_item_iv_add,
            R.id.cart_item_iv_reduce
        )

        adapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.cart_item_cb -> {
                    cartList[position].isChecked = !cartList[position].isChecked
                    (adapter.getViewByPosition(position, R.id.cart_item_cb) as CheckBox).isChecked =
                        cartList[position].isChecked
                }

                R.id.cart_item_delete -> {
                    val ids = cartList[position].id.toString()
                    viewModel.deleteCart(ids)
                    cartList.removeAt(position)
                    adapter.notifyItemRemoved(position)
                }

                R.id.cart_item_iv_add -> {
                    cartList[position].count += 1
                    viewModel.addCart(1, cartList[position].goods_id)
                    //局部刷新一个item的数量
                    (adapter.getViewByPosition(position, R.id.cart_item_tv_num) as TextView).text =
                        "${cartList[position].count}"
                }

                R.id.cart_item_iv_reduce -> {
                    viewModel.removeCart(-1, cartList[position].goods_id)
                    if (cartList[position].count > 1) {
                        cartList[position].count -= 1
                        (adapter.getViewByPosition(position, R.id.cart_item_tv_num) as TextView).text =
                            "${cartList[position].count}"
                    }
                }
            }
            totalPrice()
        }

        totalPrice()
    }

    private fun totalPrice() {
        var totalPrice = 0
        val checkList = mutableListOf<Boolean>()
        //循环list,如果其中有一项是false 就是false,全是true(选中),就是true
        cartList.forEach {
            if (it.isChecked) {
                totalPrice += it.goods_default_price * it.count
            }
            checkList.add(it.isChecked)
            Log.i("TagA", "set:$checkList")
        }
        if (checkList.size == 0) {
            dataBinding.cartCbSelectAll.isChecked = false
        } else {
            //检查set中是否有false,有就代表没有全选,全是true就代表全选
            dataBinding.cartCbSelectAll.isChecked = false !in checkList
        }
        dataBinding.cartTvTotalPrice.text = "总价:￥${totalPrice}"
    }
}